package edu.hgnc.tx.annotation.config;


import com.alibaba.druid.pool.DruidDataSource;
import edu.hgnc.tx.annotation.dao.BookDao;
import edu.hgnc.tx.annotation.service.BookService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:db.properties")
@EnableTransactionManagement
// @ComponentScan(basePackages = "edu.hgnc.tx.annotation")
public class TransactionConfig {

	private static final Log logger = LogFactory.getLog(TransactionConfig.class);

	// 注入db属性文件
	@Value("${driverClass}")
	private String driverClassName;

	@Value("${db.user}")
	private String username;

	@Value("${db.password}")
	private  String password;

	@Value("${jdbcUrl}")
	private String url;

	@Bean
	public DruidDataSource dataSource(){
		logger.debug("DruidDataSource----已成功注入--------------------");
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(driverClassName);
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		dataSource.setUrl(url);
		return dataSource;
	}

	@Bean
	public JdbcTemplate jdbcTemplate(DataSource dataSource){
		logger.debug("jdbcTemplate ====  通过 @Bean");
		return new JdbcTemplate(dataSource);
	}


	@Bean
	public BookDao bookDao(){
		logger.debug("bookDao ====  通过 @Bean");
		return new BookDao();
	}

	@Bean
	public BookService bookService(){
		logger.debug("bookService ====  通过 @Bean");
		return new BookService();
	}

	@Bean
	public PlatformTransactionManager transactionManager(DataSource dataSource){
		logger.debug("transactionManager ====  通过 @Bean");
		return new DataSourceTransactionManager(dataSource);
	}
}
